<template>
	<view>
		<js-error mode="bottom" ref="jsError"></js-error>
		<view style="background-color: #FFFFFF;padding: 10px;">
			<view style="margin-bottom: 10px;">
				 默认蓝牙打印设备
			</view>
		  <view>
		  	<text style="display: inline-block;width: 140rpx;margin-bottom: 10px;">NAME：</text> 
		  {{vuex_print.name || ''}}</view>
		  <view>
		  	<text style="display: inline-block;width: 140rpx;">ADD：</text> 
		  {{vuex_print.addId || ''}}</view>
		</view>
		
		<view style="background-color: #FFFFFF;margin-top: 10px;">
		
			<view style="text-align: center;padding: 20rpx;" v-if="deviceList.length">
				已配对蓝牙设备
			</view>
			<view
				style="padding: 20rpx;border-radius: 15rpx;margin:10px;"
				:style="{'border':device.check?'1rpx solid #aaa':'1rpx solid #000',
				'color':device.check?'#aaa':'#000'}"
				class="uni-flex uni-row flex justify-between align-center" v-for="(device,index) in deviceList" :key="index"
				>
				<!-- @click="xuanzhe(device)" -->
				<view>
					<view >{{index+1}}.</view>
					<view>
						<text style="display: inline-block;width: 100rpx;">NAME：</text> 
					{{device.name}}</view>
					<view>
						<text style="display: inline-block;width: 100rpx;">ADD：</text> 
					{{device.address}}</view>
				</view>
				<!-- printSomething(device,printTest) -->
				<view ><button type="primary" plain size="mini"
						@click="szdefault(device)">设为默认</button></view>
			</view>
			<!-- <u-empty v-if="!deviceList.length" text="没有搜索到蓝牙设备" mode="data"></u-empty> -->
			<view style="text-align: center;padding: 50px;" v-if="!deviceList.length">
				没有搜索到已配对蓝牙设备
			</view>
			<view style="text-align: center;margin-top: 20rpx;padding: 10px;" class="flex">
				<button @click="back()" type="default" class="flex-button">
					返回
				</button>
				<button @click="initPrinter()" type="primary" class="flex-button"> 
					刷新蓝牙设备
				</button>
			</view>
		</view>
		<view class="canvas-container">
			<!-- canvas  画布根据 filePathArray 图片路径数组加载图片 -->
			<canvas :style="{width: canvasWidth +'px', height: canvasHeight +'px'}" :canvas-id="'firstCanvas'+index" :id="'firstCanvas'+index" :class="'firstCanvas'+index" v-for="(item,index) in filePathArray" :key="index" />
			<view class="canvas-box">
				
			</view>
		</view>
		
	</view>
</template>
<script>
	import config from '@/common/config.js'
	import util from '@/common/fire.js'
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				type: 'text',
				startTime: false, //控制日期显示
				endTime: false, //控制日期显示
				show: false,
				model: {
				},
				filterIcon: "/static/image/filter.png",
				keyword: "",
				focus:true,
				cbarcode: '',
				printData:'',
				// show: {
				// 	setting: false
				// },
				deviceList: [],
				canvasWidth: 800,
				canvasHeight: 400,				
				filePathArray:[],
				barSizeType:'',
				selIds : '',
				prtQtys : ''
				
			};
		},
		onLoad(p) {
			// var that = this;
			// const data = JSON.parse(p.data)
			// this.selIds = data.selIds
			// this.prtQtys = data.prtQtys
			// console.log(this.selIds,this.prtQtys,'prtQtys',this.barSizeType)
			this.getdictData()
		},
		mounted() {
			var that = this;
			// #ifdef APP-PLUS
			that.initPrinter();
			// #endif
			
			// this.calculateScrollViewHeight();
		},
		computed: {
			...mapState([ 'userInfo']),
			computedScrollViewHeight() {
				return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
			},
		},
		methods: {		
			back(){
				uni.navigateBack({
					delta: 1
				})
			},
			getdictData(){
				this.$u.api.dictListData({dictType: 'bar_size_type1'}).then(res => {
					console.log(res,'res===')
					this.barSizeType = res[0]['dictValue']
					console.log(res,'res===',this.barSizeType)
					// this.getFilePathArray();
				})	
			},
			getFilePathArray(){
				const params = {
					selIds: this.keyword,
					// selIds: '5030101001',
					prtQtys: 1,
					rsPics:1,
					barType: this.vuex_config.InvBarType,
					barSizeType: this.barSizeType,
				}
				this.$u.api.mf.printSnNumber(params).then(res=>{	
					if(res.result == 'true'){
						
						this.filePathArray = res.pdfUrl
						this.renderCanvas()
					}else{
						this.$refs.jsError.showError('',res.message,'error');
					}
				})
			},
			renderCanvas() {
				// 根据 filePathArray 图片路径数组加载图片
				
				let that = this
				console.log(that.filePathArray,'that.filePathArray===')
				for (let i = 0; i < that.filePathArray.length; i++) {
					
					let filePath = this.vuex_config.baseUrl + that.filePathArray[i]
					
					console.log(filePath,'filePath')
				
					const firstCanvas = uni.createCanvasContext('firstCanvas'+ i, this);
					let scla = 0.78;
					let widthScla = 1
					uni.getImageInfo({
						src: filePath,
						async success(res) {
							console.log(res.width + "--" + res.height)
							that.canvasWidth = res.width * scla
							that.canvasHeight = res.height * scla
							console.log(res, that.canvasWidth, that.canvasHeight)
							// -20
							firstCanvas.drawImage(filePath, -50, 0, that.canvasWidth, that.canvasHeight);
							await firstCanvas.draw(false, () => {
								console.log('绘图完成');
								that.print()
							  });
							that.$nextTick(() => { //获取画布像素数据
								// setTimeout(()=>{
								// 	that.print()
								// },1000)
							})
						},
						fail(res) {
							// console.log(res)
							that.$refs.jsError.showError('',res.errMsg,'error');
						}
					})
				
				}
				
			},
			async  print() {
				if(this.deviceList.length){
					console.log('开始打印');
					let data2 = {}
					this.deviceList.forEach(item=>{
						if(item.check){
							data2 = item
						}
					})
					let that = this
					// 循环打印
					const printPromises = this.filePathArray.map((filePath, index) => {
						return new Promise((resolve, reject) => {
						uni.canvasGetImageData({
							canvasId: 'firstCanvas' + index,
							x: 0,
							y: 0,
							width: this.canvasWidth, // 确保这些值在调用前已被正确设置
							height: this.canvasHeight,
							success: (res) => {
								console.log('ImageData success:', res);
								resolve(res); // 将结果解析为 Promise 的值
							},
							fail: (res) => {
								console.error('ImageData fail:', res);
								this.$refs.jsError.showError('', res.errMsg, 'error');
								reject(res.errMsg); // 将错误信息作为 Promise 的拒绝理由
							}
						});
						});
					});
					
					const imageDatas = await Promise.all(printPromises); // 等待所有图像数据获取完成
					console.log('获取完毕',imageDatas);
					this.printSomething(data2,this.printTest,imageDatas);
					// imageDatas.forEach((imageData) => {
					// 	this.printData = imageData; // 根据需要处理打印数据，可能需要进一步调整
					// 	// 假设这是实际的打印函数
					// 	console.log('发送完毕');
					// });
					
					
					
				}else{
					this.focus = false; // 初始化 第二个输入框focus 属性
					setTimeout(() => {
						this.cbarcode = ''
						// this.focus = true; //  第二个输入框获取焦点。
					},1000)
					// this.$api.msg("请先配对蓝牙!");
					that.$refs.jsError.showError('','请先配对蓝牙!','error');
				}
				
				
				
			},
			xuanzhe(item){
				this.deviceList.forEach(i=>{
					if(i.address == item.address){
						i.check = true
					}else{
						i.check = false
					}
				})
				this.$forceUpdate();
				this.focus = false; // 初始化 第二个输入框focus 属性
				setTimeout(() => {
					this.cbarcode = ''
					// this.focus = true; //  第二个输入框获取焦点。
				},500)
			},
			szdefault(item){
				
				// this.$u.toast('切换成功');
				// this.$u.vuex('vuex_print',{
				// 	name:item.name,
				// 	addId:item.address,
				// 	data:{
				// 		...item
				// 	}
				// });
				let data = {
					name:item.name,
					addId:item.address,
					data:{
						...item
					}
				}
				
				this.$u.api.mf.wmsUserBlueSetSave(data).then(res => {
					if (res.result == 'true') {
						this.$u.toast(res.message);
						this.$u.vuex('vuex_print',data);
					}else {
						that.$refs.jsError.showError('', res.message, 'error');
					}
					console.log(res,'res===')
				})	
			},
			confirm(){
				console.log(1111);
				this.getFilePathArray();
				
				
			},
			/** 扫码*/
			showPrinterList: function() {
				var that = this;
				that.show.setting = true;
				for (var i = 0; i < that.deviceList.length; i++) {
					if (that.deviceList[i].name == that.device.name) {
						that.deviceList[i].checked = true
					}
				}
			},
			initPrinter: function() {
				var that = this;
				that.deviceList = [];
				var main = plus.android.runtimeMainActivity();
				var Context = plus.android.importClass("android.content.Context");
				var BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);
				plus.android.importClass(BManager);
				var BAdapter = BManager.getAdapter();
				plus.android.importClass(BAdapter);
				var lists = BAdapter.getBondedDevices();
				plus.android.importClass(lists);
				var iterator = lists.iterator();
				plus.android.importClass(iterator);
				while (iterator.hasNext()) {
					var d = iterator.next();
					plus.android.importClass(d);
					var temp = {
						name: d.getName(),
						address: d.getAddress(),
						status: d.getBondState(),
						uuids: d.getUuids(),
						op: d
					};
					console.log(d,'=====');
					// that.deviceList.push(temp);
					
					// 或者检查UUID是否匹配打印服务UUID
						var isPrinterUuid = false;
						if (temp.uuids) {
							for (var i = 0; i < temp.uuids.length; i++) {
								if (temp.uuids[i].toString().toLowerCase() === "00001101-0000-1000-8000-00805f9b34fb") {
									isPrinterUuid = true;
									break;
								}
							}
						}
						if (isPrinterUuid) {
							temp.isPrinter = true;
							that.deviceList.push(temp);
						}
						
					
				}
				// if(that.deviceList.length){
				// 	that.deviceList[0].check = true
				// 	this.$forceUpdate();
				// }
				this.focus = false; // 初始化 第二个输入框focus 属性
				setTimeout(() => {
					this.cbarcode = ''
					// this.focus = true; //  第二个输入框获取焦点。
				},500)
				console.log(that.deviceList,'that.deviceList==');
			},
			printSomething: function(dev, sb ,printData) {
				console.log('123')
				var that = this;
				var main = plus.android.runtimeMainActivity();
				var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				var UUID = plus.android.importClass("java.util.UUID");
				var uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
				var BAdapter = BluetoothAdapter.getDefaultAdapter();
				var device = BAdapter.getRemoteDevice(dev.address);
				plus.android.importClass(device);
				var bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
				plus.android.importClass(bluetoothSocket);
				console.log("开始连接打印机:" + dev.name);
				if (!bluetoothSocket.isConnected()) {
					bluetoothSocket.connect();
					if (bluetoothSocket.isConnected()) {
						console.log("设备已连接,开始发送打印文件");
						uni.showToast({
							title: '数据已发送',
						});
						var outputStream = bluetoothSocket.getOutputStream();
						plus.android.importClass(outputStream);
						sb(outputStream,printData);
						bluetoothSocket.close();
						if (!bluetoothSocket.isConnected()) {
							console.log("设备已关闭");
						}
					} else {
						uni.showToast({
							title: '设备连接失败',
							icon: 'error',
							duration: 2000
						});
					}
				}
				this.focus = false; 
				setTimeout(() => {
					// this.focus = true; //  第二个输入框获取焦点。
				},500)
				this.printData = ''
			},
			printTest: function(outputStream,printData) {
				try {
					if (typeof printData === 'string') {
						// 发送文本数据
						console.log(this.printData,'this.printData==');
						var that = this;
						// 100  70
						// 75  130
						// 30   20
						// var text = "! 0 480 360 378 1\r\n";
						var text = "! 0 320 160 180 1\r\n";
						text += "SPEED 1\r\n"; //打印速度 0 到 5 
						
						
						// text += "CENTER\r\n"; //居中 介绍点位置 
						text += `BARCODE 128 1 0 60 0 20 ${that.printData}\r\n`;
						// text += "TEXT 7 0 210 60 HORIZ\r\n";
						
						// text += "CENTER\r\n"; //居中 介绍点位置
						text += "SETBOLD 0\r\n"; //加粗 1加粗0不加粗
						text += "SETMAG 1 1\r\n"; //放大 宽度 高度  1-16
						text += `T 3 2 40 90 ${that.printData}\r\n`;
						text += "SETMAG 0 0\r\n";
						text += "SETBOLD 0\r\n";
			
			
						text += "SETMAG 0 0\r\n";
						text += "SETBOLD 0\r\n";
						text += "FORM\r\n";
						text += "END\r\n";
						text += "PRINT\r\n"
						// console.log(text)
						var arrayBuffer = plus.android.invoke(text, 'getBytes', 'gbk');
						outputStream.write(arrayBuffer);
						outputStream.flush();
					} else if (printData && printData[0]['data']) {
						printData.forEach(item=>{
							// var that = this;
						var imageData = item.data;
						var width = item.width;
						var height = item.height;		
						// +60
						let strCmd = this.CreatCPCLPage(576,height+60,1); 
						strCmd +=this.addCPCLImageCmd(10,10,{imageData:imageData, width:width, height:height, threshold:190,}); 
						strCmd += this.addCPCLPrint();
						console.log(strCmd,'strCmd==');
						var arrayBufferEnd = plus.android.invoke(strCmd, 'getBytes', 'gbk');
						outputStream.write(arrayBufferEnd);
						outputStream.flush();
					})
					} else {
						throw new Error('Unsupported data type');
					}
				} catch (e) {
					console.error('发送数据失败:', e);
				}
			},
			addCPCLPrint :function (){    
				var strCmd = 'PRINT\n';     
				return strCmd;
			},
			CreatCPCLPage :function (width, height, printNum, rotation=0, offset=-5) {    
				var strCmd = '! '+offset+' 200 200 '+ height +' '+printNum+'\n';  
				strCmd+="PAGE-WIDTH "+width+'\n'; 
				if(rotation==1)
					strCmd+="ZPROTATE90\n";
				else if(rotation==2)
					strCmd+="ZPROTATE180\n";
				else if(rotation==3)
					strCmd+="ZPROTATE270\n";
				else
					strCmd+="ZPROTATE0\n";
				return strCmd;
			},
			addCPCLImageCmd :function (x,y,data) {
				var strImgCmd = '';
				const threshold = data.threshold || 180;
				let myBitmapWidth = data.width,
					myBitmapHeight = data.height;
				let len = parseInt((myBitmapWidth + 7) / 8);//一行的数据长度
				//console.log('len=',len);
				//console.log('myBitmapWidth=',myBitmapWidth);
				//console.log('myBitmapHeight=',myBitmapHeight);
				let ndata = 0;
				let i = 0;
				let j = 0;                                
				let sendImageData = new ArrayBuffer(len * myBitmapHeight);
				sendImageData = new Uint8Array(sendImageData);
				let pix = data.imageData;
			
				for (i = 0; i < myBitmapHeight; i++)
				{
					for (j = 0; j < len; j++)
					{
						sendImageData[ndata + j] = 0;
					}
					for (j = 0; j < myBitmapWidth; j++)
					{
						const grayPixle1 = this.grayPixle(pix.slice((i * myBitmapWidth + j)*4, (i * myBitmapWidth + j)*4+3));                        
						if (grayPixle1 < threshold )
							sendImageData[ndata + parseInt(j / 8)] |=(0x80 >> (j % 8));
															
					}                    
					ndata += len;
				}
				//console.log('sendImageData=',sendImageData);
				//CPCL指令图片数据 
				strImgCmd += 'EG '+ len+' '+myBitmapHeight+' '+ x +' '+ y +' ';
				for(i=0;i<sendImageData.length;i++){
					strImgCmd += this.Hex2Str(sendImageData[i]);
				}
				strImgCmd +='\n';    
				// console.log(strImgCmd);
				return strImgCmd;
			},
			grayPixle : function (pix) {
				return pix[0] * 0.299 + pix[1] * 0.587 + pix[2] * 0.114;
			},
			Hex2Str : function (num) {  
				if(num.toString(16).length < 2)     return "0"+num.toString(16);  
				else    
					return num.toString(16);
			},
			printBox: function(p, l, w, k, s) { //起点坐标、长高、宽、线宽、显示(上左下右)
				var text = "";
				if (s.t) {
					text = text.concat("L ", p.x, " ", p.y, " ", w, " ", p.y, " ", k, "\r\n");
				}
				if (s.l) {
					text = text.concat("L ", p.x, " ", p.y, " ", p.x, " ", p.y + l, " ", k, "\r\n");
				}
				if (s.b) {
					text = text.concat("L ", p.x, " ", p.y + l, " ", w, " ", p.y + l, " ", k, "\r\n");
				}
				if (s.r) {
					text = text.concat("L ", w, " ", p.y + l, " ", w, " ", p.y, " ", k, "\r\n");
				}
				return text;
			},
			cutLine: function(p, str) {
				var r = "";
				var max = 18;
				var n = parseInt(str.length / max);
				for (var i = 0; i < n; i++) {
					var temp = str.substr(i * max, max);
					r += "T 3 0 " + p.x + " " + (p.y + 40 * i) + " " + temp + "\r\n"
				}
				var w = str.substr(n * max);
				r += "T 3 0 " + p.x + " " + (p.y + 40 * n) + " " + w + "\r\n";
				return r;
			},
			printLineList: function(p, list) {
				var r = "";
				for (var i = 0; i < list.length && i < 5; i++) {
					r += "T 3 0 " + p.x + " " + (p.y + 40 * i) + " " + list[i] + "\r\n"
				}
				return r;
			},
			printLineList2: function(p, list) {
				var r = "";
				for (var i = 0; i < list.length && i < 10; i = i + 2) {
					r += "T 3 0 " + p.x + " " + (p.y + 60 * i) + " " + list[i] + "\r\n";
					if ((i + 1) < list.length) {
						r += "T 3 0 " + (p.x + 150) + " " + (p.y + 60 * i) + " " + list[i + 1] + "\r\n";
					}
				}
				return r;
			},
			mySleep: async function(time) {
				await this.mypromise(time);
			},
			mypromise: function(time) {
				return new Promise((resolve) => setTimeout(resolve, time));
			}
		}
	};
</script>
<style lang="scss" scoped>
	$all_width: 96rpx;
	$all_height: 96rpx;
	.movable-area1 {
		z-index: 888;
		height: 97vh;
		width: 650rpx;
		position: fixed;
		right: $all_width;
		top: -($all_height + 100rpx);
		pointer-events: none; //此处要加，鼠标事件可以渗透
		.movable-view {
			width: $all_width;
			height: $all_height;
			pointer-events: auto; //恢复鼠标事件
			image {
				width: $all_width;
				height: $all_height;
			}
		}
	}
	.text-border{
		border:2px solid  rgb(170, 170, 170); 
		border-radius: 5px;
		position: relative;
		padding-top: 20rpx;
		margin-top: 40rpx;
		padding-left: 20rpx;
		.text{
			position: absolute;
			background-color: #fff;
			padding: 10rpx 10rpx;
			top: -25rpx;
			right: 30rpx;
		}
	}
	.custom-style{
		// background-color: rgba(25, 190, 107, 0.7);
		
	}	
	.text-xxl{
		font-size:60rpx;
	}
	.cu-bar {
		min-height: 60px;
	}

	.cu-btn {
		font-size: 16px;
		height: 40px;
	}

	.foot {
		background: #fff;
	}

	.cu-item {
		flex-wrap: wrap;
		padding: 8px 15px !important;
	}

	.title {
		width: 230rpx;
	}

	.cu-modal-slot {
		margin: 42rpx 32rpx 20rpx 32rpx;
		height: 100vh;
		position: relative;
	}

	.cu-modal-header {
		font-size: 38rpx;
		color: #3d3d3d;
		line-height: 40rpx;
		text-align: left;
		font-weight: 500;
	}

	.button {
		font-size: 32rpx;
		color: #666666;
		line-height: 40rpx;
		padding: 12rpx 40rpx;
		margin-bottom: 20rpx;
		background: #e2e2e2;
		border-radius: 180rpx;
	}

	.button:hover {
		background: #3e97b0;
		color: #ffffff;
	}

	.cu-modal-search-title {
		margin: 32rpx 0rpx 20rpx 0rpx;
		text-align: left;
		font-size: 32rpx;
		color: #999999;
		line-height: 40rpx;
	}

	.cu-dialog {
		background: #ffffff;
	}

	.cu-modal-footer {
		padding: 32rpx 32rpx;
		width: 100%;

		.cu-btn {
			width: 50%;
		}
	}

	.bg-confirm {
		background: #3e97b0;
		color: #ffffff;
	}
	
	
	page {
		padding: 0;
		margin: 0;
	}
	
	.picked {
		background-color: lavender;
	}
	.canvas-container {
	  position: relative;
	  width: 100%; /* 或具体宽度 */
	  height: 100%; /* 或具体高度 */
	}
	
	.canvas-box {
	  position: absolute;
	  top: 0;
	  left: 0;
	  width: 100%; /* 与canvas宽度一致 */
	  height: 100%; /* 与canvas高度一致 */
	  background-color: #fff; /* 半透明黑色背景 rgba(0, 0, 0, 0.5); */
	  pointer-events: none; /* 允许鼠标事件穿透 */
	}
	.flex-button{
		width: 40%;
	}
</style>